const util = require('util');
const fs = require('fs');
const path = require('path');
const OAuth = require('co-wechat-oauth');
const WechatAPI = require('co-wechat-api');

const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);

const { appid, secret } = require('./config/server');

module.exports = app => {
	app.beforeStart(async () => {
		app.wechatOauth = new OAuth(
			appid,555
			secret,
			async (openid) => {
				const txt = await readFile(path.resolve('wechat_logs', openid + ':access_token.txt'), 'utf8');
				return JSON.parse(txt);
			},
			async (openid, token) => {
				await writeFile(path.resolve('wechat_logs', openid + ':access_token.txt'), JSON.stringify(token));
			}
		);
		app.wechatApi = new WechatAPI(
			appid,
			secret,
			async () => {
				const txt = await readFile(path.resolve('wechat_logs', 'access_token.txt'), 'utf8');
				return JSON.parse(txt);
			},
			async token => {
				await writeFile(path.resolve('wechat_logs', 'access_token.txt'), JSON.stringify(token));
			}
		);
		try {
			await app.wechatApi.getAccessToken();
		} catch (err) {
			app.logger.error(err);
			console.log(`${err.name} => ${err.code}`);
		}
	});
};
